<template>
<div style="overflow: hidden">
  <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
    <el-breadcrumb-item :to="{ path:'/blank' }"><i class="el-icon-message-solid"></i>系统管理</el-breadcrumb-item>
    <el-breadcrumb-item>公告管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-divider></el-divider>
  <el-row style="text-align: left">
    <el-input style="width: 220px;margin-right: 10px" @change="getNoticeArrByContent" placeholder="请选择输入查询内容" prefix-icon="el-icon-search" v-model="inputs"></el-input>
    <el-button type="success" size="medium" icon="el-icon-search">搜索</el-button>
  </el-row>
  <el-row style="text-align: left;margin: 10px 0">
    <el-button type="primary" icon="el-icon-plus" @click="dialogFormVisibleAdd = true">添加公告</el-button>
    <el-button type="danger" icon="el-icon-delete" v-if="isMultipleSelection" @click="openByIds">删除</el-button>
  </el-row>
  <el-table :border="true" ref="multipleTable" :data="noticeArr" tooltip-effect="dark" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="60" align="center"></el-table-column>
    <el-table-column
        label="公告内容" prop="content" show-overflow-tooltip header-align="center">
    </el-table-column>
    <el-table-column
        label="创建时间" prop="gmtCreate" width="180" show-overflow-tooltip align="center">
    </el-table-column>
    <el-table-column
        label="更新时间" prop="gmtModified" width="180" show-overflow-tooltip align="center">
    </el-table-column>
    <el-table-column  label="是否为最新公告" header-align="center" align="center" width="180">
      <template slot-scope="scope">{{scope.row.status==1?"最新公告":"过期公告"}}</template>
    </el-table-column>
    <el-table-column  label="操作" header-align="center" align="center" width="100">
      <template slot-scope="scope">
        <el-button type="primary" size="mini" icon="el-icon-edit" circle
                   @click="openEditDialog(scope.row)"></el-button>
        <el-button type="danger" size="mini" icon="el-icon-delete" circle
                   @click="openDelete(scope.row)"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <div style="text-align: right;margin: 10px auto">
    <el-pagination
        layout="total,prev, pager, next"
        @current-change="changePage"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize">
    </el-pagination>
  </div>

  <el-dialog title="公告修改" :visible.sync="dialogFormVisible" width="500px">
    <el-form :model="editForm" :rules="rules" ref="editForm" :label-width="formLabelWidth" align="left" style="margin: -10px 0 -20px 0">
      <el-form-item label="公告内容:" prop="content">
        <el-input v-model="editForm.content" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="是否禁用" prop="status" align="left">
        <el-switch
            v-model="editForm.status"
            active-value="0"
            inactive-value="1"
            active-color="#13ce66">
        </el-switch>

      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitEditForm" >确 定</el-button>
    </div>
  </el-dialog>


  <el-dialog title="公告新增" :visible.sync="dialogFormVisibleAdd" width="500px">
    <el-form :model="editFormAdd" :rules="rules" ref="editForm" :label-width="formLabelWidth" align="left" style="margin: -10px 0 -20px 0">
      <el-form-item label="公告内容:" prop="content">
        <el-input v-model="editFormAdd.content" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="是否禁用" prop="status" align="left">
          <el-switch
              v-model="editFormAdd.status"
              active-value="0"
              inactive-value="1"
              active-color="#13ce66"
              >
          </el-switch>

      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
      <el-button type="primary" @click="submitEditFormAdd('editForm')" >确 定</el-button>
    </div>
  </el-dialog>

</div>
</template>

<script>
export default {
  data() {
    return {
      total:0,
      pageSize:0,
      currentPage:1,
      inputs:'',
      noticeArr: [],
      multipleSelection: [],
      dialogFormVisible: false,
      dialogFormVisibleAdd: false,
      isMultipleSelection: false,
      editForm: {
        id: '',
        content: '',
        status:''
      },
      editFormAdd: {
        content: '',
        status:''
      },
      formLabelWidth: '120px',
      rules: {
        id: [
          {required: true, message: '请输入id', trigger: 'blur'},
          {min: 0, max: 10, message: '长度在 2 到 25 个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入正文', trigger: 'blur'},
          {min: 0, max: 255, message: '长度在 2 到 25 个字符', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请输入正文', trigger: 'blur'},
          {pattern:/^([01])$/,message:'请输入以字母和数字组成的密码',trigger: 'blur'}
        ]
      }
    }
  },

  methods: {

    //新增公告
    submitEditFormAdd(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.editFormAdd)
          let url = 'http://localhost:9283/notice/add-new';
          let jwt = localStorage.getItem("localJwt");
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.editFormAdd);
          console.log('formData = ' + formData);

          this.axios
              .create({
                'headers':{
                  'Authorization':jwt
                }
              })
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                message: '新增公告成功！',
                type: 'success'
              });
              this.dialogFormVisibleAdd = false;
              this.getNoticeArr()
              if (jsonResult.jwt!=null){
                localStorage.setItem("localJwt",jsonResult.jwt);
              }
            }else if(jsonResult.state==70100){
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
              this.$router.push('/')
            }  else if (jsonResult.state == 40400){
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                  console.log(action);
                  this.dialogFormVisibleAdd = false;
                  this.getNoticeArr();
                }
              });
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定'
              });
            }
          });
        }else {
          console.log('error submit!!');
          return false;
        }
      })


    },
    openEditDialog(notice){
      let url = "http://localhost:9283/notice/standard?id="+notice.id;
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else {
          this.$alert(jsonResult.message,"错误",{
            confirmButtonText:'确定',
            callback: action => {
              console.log(action)
              this.getNoticeArr()
            }
          })
        }
      })
    },
    submitEditForm() {
      console.log(this.editForm)
      let url = 'http://localhost:9283/notice/updateInfo';
      console.log('url = ' + url);
      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);
      let jwt = localStorage.getItem("localJwt");

      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改公告成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.getNoticeArr()
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              console.log(action);
              this.dialogFormVisible = false;
              this.getNoticeArr();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定'
          });
        }
      });
    },
    openByIds(){
      if(this.multipleSelection.length<1){
        alert("您未选中任何公告")
        return;
      }
      this.$confirm('此操作将永久这些公告公告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteByIds();
      }).catch(() => {
      });
    },
    deleteByIds(){
      //deleteByIds
      let url = "http://localhost:9283/notice/deleteByIds";
      let jwt = localStorage.getItem("localJwt");
      let ids = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        ids[i] = this.multipleSelection[i].id;
      }
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .post(url,ids).then((response)=> {
        let jsonResult = response.data;
        console.log("11111")
        if(response.data.state==20000){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.getNoticeArr();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else{
          alert(response.data.message);
          this.code(this.options);
        }
      })
    },
    openDelete(notice){
      this.$confirm('此操作将永久此公告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.openDeleteById(notice)
      }).catch(() => {
      });
    },
    openDeleteById(notice){
      let url = "http://localhost:9283/notice/deleteById";
      let formDate = "id="+notice.id;
      console.log(url);
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          }).post(url,formDate).then((response)=> {
            let jsonResult = response.data;
            console.log("11111")
        if(response.data.state==20000){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.getNoticeArr();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else{
          alert(response.data.message);
          this.code(this.options);
        }
      })
    },
    changePage(value){
      if(this.inputs.trim()==''){
        console.log(this.currentPage)
        this.$router.replace("?page="+value);
        this.getNoticeArr();
      }else {
        this.$router.replace("?page="+value);
        this.getNoticeArrByContent();
      }

    },
    getNoticeArr(){
      let page = this.$router.currentRoute.query.page;
      console.log(page)
      if(!page){
        page=1;
      }
      let url = "http://localhost:9283/notice/list?page="+page;
      console.log(url);
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          }).get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.noticeArr = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          this.inputs = '';
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else {
          this.$alert(jsonResult.message,"错误",{
            confirmButtonText:'确定'
          })
        }
      })
    },
    getNoticeArrByContent(){
      let page = this.$router.currentRoute.query.page;
      console.log(page)
      if(!page){
        page=1;
      }
      let url = "http://localhost:9283/notice/list-content?page="+page+"&content="+this.inputs;
      console.log(url);
      let jwt = localStorage.getItem("localJwt");
      this.axios
          .create({
            'headers':{
              'Authorization':jwt
            }
          })
          .get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.noticeArr = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else {
          this.$alert(jsonResult.message,"错误",{
            confirmButtonText:'确定'
          })
        }
      })
    },
    handleSelectionChange(val) {
      if (val.length==0){
        this.isMultipleSelection = false;
      }else{
        this.isMultipleSelection = true;
      }
      this.multipleSelection = val;
    }
  },
  mounted() {
    this.getNoticeArr();
  }
}
</script>

<style scoped>

</style>
